<?php

class Silk_Http_Response {

    protected $_buffered = true;
    protected $_compression = 'gzip';

    protected $_headers = array();
    protected $_body = '';

    public function __construct(array $pConfig=array()){

	if (array_key_exists('buffered', $pConfig))
	    $this->_buffered = $pConfig['buffered'];

	if (array_key_exists('compression', $pConfig))
	    $this->_compression = strtolower($pConfig['compression']);

    }

    public function setHeader($pHeader, $pValue){
	if (!headers_sent())
	    $this->_headers[$pHeader] = $pValue;
    }

    public function hasHeader($pHeader){

	foreach ($this->_headers as $header => $val){
	    if (strtolower($header) == strtolower($pHeader)) return true;
	}

	return false;
    }

    public function hasContent(){
	return (strlen($this->_body) > 0);
    }

    public function prependBody($pContent){

	$this->_body = $pContent . $this->_body;

    }

    public function appendBody($pContent){

	$this->_body .= $pContent;
    }

    public function getBody(){

	return $this->_body;

    }

    public function setBody($pContent){

	$this->_body = $pContent;

    }

    public function clearBody(){

	$this->_body = '';

    }

    public function flush(){
	logdebug("Silk_Http_Response.flush: Called");

	if ($this->_compression){
	    switch ($this->_compression){
		case 'gzip':
		    $compression_callback = 'ob_gzhandler';
		    break;
		default:
		    $compression_callback = null;
	    }
	} else
	    $compression_callback = null;

	ob_start($compression_callback);

	foreach ($this->_headers as $header => $val){
	    logdebug("Silk_Http_Response.flush: header {$header}:{$val}");
	    header("{$header}: {$val}");
	}

	echo $this->_body;

	ob_end_flush();

    }

}

?>